import request from '@/utils/request'
import type { BaseResponse, PaginationResponse } from '@/types/common/response'

// ==================== 类型定义 ====================

/**
 * 会话类型
 */
export interface ChatSession {
  id: number
  memberId: number
  staffId?: number
  type: 'CUSTOMER_SERVICE' | 'COACH_CONSULT'
  status: 'WAITING' | 'ACTIVE' | 'CLOSED'
  title: string
  lastMessageId?: number
  lastMessageAt?: string
  unreadCount: number
  staffUnreadCount: number
  rating?: number
  ratingComment?: string
  closedAt?: string
  closedBy?: number
  createdAt: string
  updatedAt: string
  member?: any
  staff?: any
  lastMessage?: any
}

/**
 * 消息类型
 */
export interface ChatMessage {
  id: number
  sessionId: number
  senderId: number
  senderName: string
  senderAvatar: string
  senderType: 'MEMBER' | 'STAFF'
  messageType: 'TEXT' | 'IMAGE' | 'FILE' | 'SYSTEM'
  content: string
  fileUrl?: string
  fileName?: string
  fileSize?: number
  imageWidth?: number
  imageHeight?: number
  isRead: boolean
  isRecalled: boolean
  createdAt: string
  readAt?: string
}

/**
 * 快捷回复类型
 */
export interface QuickReply {
  id: number
  staffId?: number
  title: string
  content: string
  category: string
  sortOrder: number
  createdAt: string
}

/**
 * 客服统计类型
 */
export interface ChatStatistics {
  staffId: number
  staffName: string
  totalSessions: number
  activeSessions: number
  closedSessions: number
  avgResponseTime: number
  avgRating: number
  totalMessages: number
  avgSessionDuration: number
  ratingDistribution: Record<string, number>
  sessionsPerDay: Record<string, number>
  dateRange: {
    startDate: string
    endDate: string
  }
}

// ==================== 请求参数类型 ====================

export interface CreateSessionReq {
  type: 'CUSTOMER_SERVICE' | 'COACH_CONSULT'
  title?: string
}

export interface SessionListReq {
  status?: string
  type?: string
  page?: number
  pageSize?: number
}

export interface CloseSessionReq {
  rating?: number
  ratingComment?: string
}

export interface TransferSessionReq {
  toStaffId: number
}

export interface SendMessageReq {
  sessionId: number
  messageType: 'TEXT' | 'IMAGE' | 'FILE' | 'SYSTEM'
  content?: string
  fileUrl?: string
  fileName?: string
  fileSize?: number
  imageWidth?: number
  imageHeight?: number
}

export interface MessageListReq {
  sessionId: number
  page?: number
  pageSize?: number
  beforeId?: number
}

export interface SearchMessagesReq {
  sessionId?: number
  keyword: string
  page?: number
  pageSize?: number
}

export interface MarkReadReq {
  messageIds: number[]
}

export interface QuickReplyReq {
  title: string
  content: string
  category: string
  sortOrder?: number
}

export interface StatisticsReq {
  staffId?: number
  startDate?: string
  endDate?: string
}

// ==================== API接口 ====================

/**
 * 聊天API
 */
export const chatApi = {
  // ========== 会话管理 ==========
  
  /**
   * 创建会话
   */
  createSession(data: CreateSessionReq) {
    return request.post<BaseResponse<ChatSession>>('/api/v1/chat/sessions', data)
  },

  /**
   * 获取会话列表
   */
  getSessionList(params: SessionListReq) {
    return request.get<BaseResponse<PaginationResponse<ChatSession>>>('/api/v1/chat/sessions', { params })
  },

  /**
   * 获取会话详情
   */
  getSession(id: number) {
    return request.get<BaseResponse<ChatSession>>(`/api/v1/chat/sessions/${id}`)
  },

  /**
   * 关闭会话
   */
  closeSession(id: number, data: CloseSessionReq) {
    return request.post<BaseResponse<null>>(`/api/v1/chat/sessions/${id}/close`, data)
  },

  /**
   * 获取等待接入的会话列表（客服端）
   */
  getWaitingSessions() {
    return request.get<BaseResponse<PaginationResponse<ChatSession>>>('/api/v1/chat/staff/waiting')
  },

  /**
   * 客服接入会话
   */
  takeSession(id: number) {
    return request.post<BaseResponse<null>>(`/api/v1/chat/staff/sessions/${id}/take`)
  },

  /**
   * 转接会话
   */
  transferSession(id: number, data: TransferSessionReq) {
    return request.post<BaseResponse<null>>(`/api/v1/chat/staff/sessions/${id}/transfer`, data)
  },

  // ========== 消息管理 ==========

  /**
   * 发送消息
   */
  sendMessage(data: SendMessageReq) {
    return request.post<BaseResponse<ChatMessage>>('/api/v1/chat/messages', data)
  },

  /**
   * 获取消息列表
   */
  getMessageList(params: MessageListReq) {
    return request.get<BaseResponse<PaginationResponse<ChatMessage>>>('/api/v1/chat/messages', { params })
  },

  /**
   * 搜索消息
   */
  searchMessages(params: SearchMessagesReq) {
    return request.get<BaseResponse<PaginationResponse<ChatMessage>>>('/api/v1/chat/messages/search', { params })
  },

  /**
   * 标记消息已读
   */
  markMessagesAsRead(data: MarkReadReq) {
    return request.post<BaseResponse<null>>('/api/v1/chat/messages/read', data)
  },

  /**
   * 撤回消息
   */
  recallMessage(id: number) {
    return request.post<BaseResponse<null>>(`/api/v1/chat/messages/${id}/recall`)
  },

  /**
   * 获取未读消息数
   */
  getUnreadCount() {
    return request.get<BaseResponse<{ count: number }>>('/api/v1/chat/unread-count')
  },

  /**
   * 上传聊天文件
   */
  uploadChatFile(formData: FormData) {
    return request.post<BaseResponse<any>>('/api/v1/chat/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // ========== 快捷回复 ==========

  /**
   * 获取快捷回复列表
   */
  getQuickReplyList(params?: { category?: string }) {
    return request.get<BaseResponse<{ list: QuickReply[] }>>('/api/v1/chat/quick-replies', { params })
  },

  /**
   * 创建快捷回复
   */
  createQuickReply(data: QuickReplyReq) {
    return request.post<BaseResponse<QuickReply>>('/api/v1/chat/quick-replies', data)
  },

  /**
   * 更新快捷回复
   */
  updateQuickReply(id: number, data: QuickReplyReq) {
    return request.put<BaseResponse<QuickReply>>(`/api/v1/chat/quick-replies/${id}`, data)
  },

  /**
   * 删除快捷回复
   */
  deleteQuickReply(id: number) {
    return request.delete<BaseResponse<null>>(`/api/v1/chat/quick-replies/${id}`)
  },

  // ========== 在线状态 ==========

  /**
   * 获取在线状态
   */
  getOnlineStatus(userIds?: number[]) {
    return request.get<BaseResponse<{ onlineUsers: number[] }>>('/api/v1/chat/online-status', {
      params: { userIds: userIds?.join(',') }
    })
  },

  // ========== 客服统计 ==========

  /**
   * 获取客服统计
   */
  getStaffStatistics(params: StatisticsReq) {
    return request.get<BaseResponse<ChatStatistics>>('/api/v1/chat/staff/statistics', { params })
  }
}

// 导出兼容旧代码的函数（方便迁移）
export const createSession = chatApi.createSession
export const getSessionList = chatApi.getSessionList
export const getSession = chatApi.getSession
export const closeSession = chatApi.closeSession
export const getWaitingSessions = chatApi.getWaitingSessions
export const takeSession = chatApi.takeSession
export const transferSession = chatApi.transferSession
export const sendMessage = chatApi.sendMessage
export const getMessageList = chatApi.getMessageList
export const searchMessages = chatApi.searchMessages
export const markMessagesAsRead = chatApi.markMessagesAsRead
export const recallMessage = chatApi.recallMessage
export const getUnreadCount = chatApi.getUnreadCount
export const uploadChatFile = chatApi.uploadChatFile
export const getQuickReplyList = chatApi.getQuickReplyList
export const createQuickReply = chatApi.createQuickReply
export const updateQuickReply = chatApi.updateQuickReply
export const deleteQuickReply = chatApi.deleteQuickReply
export const getOnlineStatus = chatApi.getOnlineStatus
export const getStaffStatistics = chatApi.getStaffStatistics
